import { defineStore } from 'pinia';
import { store } from '@/stores';
import { login as LoginFn, userAuth } from '@/api/modules/user';

import { createSocket } from '@/hooks/socket';
export interface IUserState {
  userInfo: any;
  token: string;
  projectPermissions: string[];
  auth: any;
  appInfo: any;
  orgInfo: any;
}
export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => {
    return {
      userInfo: null,
      token: '',
      auth: null,
      appInfo: null,
      orgInfo: null,
      projectPermissions: [],
    };
  },
  getters: {
    getProjectPermissions(): string[] {
      return this.projectPermissions;
    },
    getPermissions(): string[] {
      if (this.appInfo && this.appInfo.allFunctionList) {
        return this.appInfo.allFunctionList.map((item: any) => item.fuceCode);
      }
      return [];
    },
    getUserInfo(): any {
      return this.userInfo;
    },
    getToken(): string {
      return this.token;
    },
    getAuth(): any {
      return this.auth;
    },
    getOrgInfo(): any {
      return this.orgInfo;
    },
    getAppInfo(): object {
      return this.appInfo;
    },
  },
  actions: {
    setProjectPermissions(permissions: any) {
      this.projectPermissions = permissions;
    },
    setUserInfo(info: any) {
      this.userInfo = info;
    },
    setToken(token: string) {
      this.token = 'Bearer' + token;
      uni.setStorageSync('Token', this.token);
    },
    setAuth(auth: any) {
      this.auth = auth;
    },
    setOrgInfo(orgInfo: any) {
      this.orgInfo = orgInfo;
    },
    setAppInfo(info: any) {
      this.appInfo = info;
    },
    async login(params: any) {
      // LoginFn(params)
      //   .then((response: any) => {
      //     const { user_info, access_token } = response;
      //     this.setUserInfo(user_info);
      //     this.setToken(access_token);
      //     userAuth(user_info.userId).then((auth: any) => {
      //       this.setAuth(auth.userOrgList);
      //     });
      //   })
      //   .catch((e) => {
      //     return Promise.reject(e);
      //   });
      try {
        const response: any = await LoginFn(params);
        console.log('response');
        console.log(response);
        const { user_info, access_token } = response;
        this.setUserInfo(user_info);
        this.setToken(access_token);
        // 查询用户权限
        const auth: any = await userAuth(user_info.userId);
        this.setUserInfo({ ...user_info, realnameStatus: auth.realnameStatus });
        this.setAuth(auth.userOrgList);
        const _orgInfo = auth.userOrgList.filter((item: any) =>
          (item.appList || []).some((el: any) => el.appCode === 'CTMS')
        );
        this.setOrgInfo(_orgInfo[0]);
        const defaultOrg = _orgInfo[0];
        const defaultApp = (defaultOrg?.appList || []).find(
          (item: any) => item.appCode === 'CTMS'
        );
        this.setAppInfo(defaultApp);
        // 登录成功后，重新建立socket链接
        createSocket();
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
});

// 需要在设置之外使用
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
